#include "ResourceManager.h"

using namespace std;

ResourceManager::ResourceManager(void)
{
}

ResourceManager::~ResourceManager(void)
{
	for (int i = 0; i < m_NumModel; i++)
	{
		SAFE_DEL(m_Model[i]);
	}
	SAFE_DEL(m_Model);
	for (int i = 0; i < m_NumTexture-1; i++)
	{
		SAFE_DEL(m_Texture[i]);
	}
	SAFE_DEL(m_Texture);
	for (int i = 0; i < m_NumShader; i++)
	{
		SAFE_DEL(m_Shader[i]);
	}
	SAFE_DEL(m_Shader);

}

ResourceManager* ResourceManager::s_Instance = 0;
ResourceManager* ResourceManager::GetInstance()
{
	if (!s_Instance)
	{
		s_Instance = new ResourceManager();
	}
	return s_Instance;
}

Model* ResourceManager::GetModel(char* ID)
{
	for (int i = 0; i < m_NumModel; i++)
	{
		if (strcmp(m_Model[i]->GetID(),ID) == 0)
			return m_Model[i];
	}
}

void ResourceManager::AddTexture(char* ID, Texture* texture)
{
	m_Texture[m_NumTexture] = texture;
	m_Texture[m_NumTexture]->SetID(ID);
	m_NumTexture++;
}

Texture* ResourceManager::GetTexture(char* ID)
	{
	for (int i = 0; i < m_NumTexture; i++)
	{
		if (strcmp(m_Texture[i]->GetID(),ID) == 0)
			return m_Texture[i];
	}
}

Shader* ResourceManager::GetShader(char* ID)
{
	for (int i = 0; i < m_NumShader; i++)
	{
		if (strcmp(m_Shader[i]->GetID(),ID) == 0)
			return m_Shader[i];
	}
}

void ResourceManager::Load(char * file)
{
	FILE * pFile;
	FileManager* FM = FileManager::GetInstance();
	char ID[10], path[100], pathFS[100], pathVS[100], state[10], filter[10];
	int isTexture2D;
	int numState;
	pFile = fopen(file, "r");
	fscanf(pFile, "#NrModel: %d\n",&m_NumModel);
	m_Model = new Model*[m_NumModel];
	for (int i = 0; i < m_NumModel; i++)
	{
		fscanf(pFile, "ID: %s Path: %s\n", ID, path);
		m_Model[i] = new Model;
		m_Model[i]->LoadModel(ID, FM->Open(path));
	}

	fscanf(pFile, "#NrTexture: %d\n", &m_NumTexture);
	m_Texture = new Texture*[m_NumTexture];
	for (int i = 0; i < m_NumTexture; i++)
	{
		fscanf(pFile, "ID: %s Path: %s IsTexture2D: %d Filter: %s", ID, path, &isTexture2D, filter);
		m_Texture[i] = new Texture;
		if (strcmp(filter,"CLAMP") == 0 )
			m_Texture[i]->LoadTexture(ID, FM->Open(path), isTexture2D, GL_CLAMP_TO_EDGE);
		else
			m_Texture[i]->LoadTexture(ID, FM->Open(path), isTexture2D, GL_REPEAT);
		fscanf(pFile, "\n");
	}

	fscanf(pFile, "#NrShader: %d\n", &m_NumShader);
	m_Shader = new Shader*[m_NumShader];
	for (int i = 0; i < m_NumShader; i++)
	{
		fscanf(pFile, "ID: %s PathVS: %s PathFS: %s NrState: %d ", ID, pathVS, pathFS, &numState);
		m_Shader[i] = new Shader;
		m_Shader[i]->Init(ID, FM->Open(pathVS), FM->Open(pathFS));
		for (int j = 0; j < numState; j++)
		{
			fscanf(pFile,"%s", state);
			if (strcmp("CULLING", state) == 0)
				m_Shader[i]->AddState(GL_CULL_FACE);
			if (strcmp("DEPTH", state) == 0)
				m_Shader[i]->AddState(GL_DEPTH_TEST);
			if (strcmp("BLEND", state) == 0)
				m_Shader[i]->AddState(GL_BLEND);
		}
		fscanf(pFile, "\n");
	}
	delete[] file;


}